//
//  TXBaseViewController.swift
//  SwiftLibrary
//
//  Created by xicheng on 16/3/7.
//  Copyright © 2016年 taurusxi. All rights reserved.
//

import UIKit
//import IQKeyboardManagerSwift
import SVProgressHUD
import SwiftyJSON
//import Material
import SDAutoLayout


class TXNavigationBar: UIVisualEffectView {
  
  
  fileprivate var lineView:UIView! = nil
  
  
  fileprivate var whiteLayer:CALayer? = nil
  
  internal var needWhiteBg:Bool = false {
    
    
    didSet {
      if needWhiteBg {
        if self.whiteLayer == nil {
          self.whiteLayer = CALayer()
          self.whiteLayer?.backgroundColor = UIColor.white.cgColor
          self.whiteLayer?.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)
          
          self.layer.insertSublayer(self.whiteLayer!, at: 0)
        }
        
      }else {
        self.whiteLayer?.removeFromSuperlayer()
        
      }
      
      
    }
    
  }
  
  internal var titleClickListener:(()->())? = nil {
    
    
    didSet {
      if let _ = titleClickListener {
        titleView.isUserInteractionEnabled = true
      }else{
        titleView.isUserInteractionEnabled = false
      }
      
    }
  }
  
  
  internal var title:String?  {
    
    get{
      return titleView.text
    }
    
    set(newValue){
      if newValue == nil {
        titleView.text = nil
        titleView.isHidden = true
      }else{
        titleView.isHidden = false
        titleView.text = newValue
      }
    }
    
  }
  
  internal lazy var titleView:UILabel = {
    let titleView = UILabel()
    titleView.textColor = UIColor.black
    titleView.font = UIFont.systemFont(ofSize: 18)
    return titleView
  }()
  
  internal var leftBt:UIButton? {
    
    didSet{
      
      if oldValue != nil {
        oldValue?.removeFromSuperview()
      }
      if leftBt != nil {
        self.addSubview(leftBt!)
      }
    }
    
  }
  
  internal var rightBt:UIButton? {
    didSet{
      if oldValue != nil {
        oldValue?.removeFromSuperview()
      }
      
      if rightBt != nil {
        self.addSubview(rightBt!)
      }
    }
    
  }
  
  convenience init(){
    let blurEffet = UIBlurEffect(style:.extraLight)
    //        self.init(frame:CGRectMake(0, 0, kMainScreenWidth, 64))
    self.init(effect:blurEffet)
    
  }
  
  
  override init(effect: UIVisualEffect?) {
    super.init(effect: effect)
    self.frame = CGRect(x: 0, y: 0, width: kMainScreenWidth, height: kNaviHeight)
    self.lineView = UIView(frame: CGRect(x: 0,y: frame.height-kSingleLinePx,width: frame.width,height: kSingleLinePx))
    self.lineView.backgroundColor = UIColor.navigationLineColor()
    addSubview(lineView)
    
    
    addSubview(self.titleView)
    self.titleView.sd_layout().topSpaceToView(self,kStatusBarHeight)?.centerXEqualToView(self)?.heightIs(kNaviHeight - kStatusBarHeight)
    self.titleView.setSingleLineAutoResizeWithMaxWidth(240)
    
    self.titleView.addGestureRecognizer(UITapGestureRecognizer(target: self,action: #selector(TXNavigationBar.titleViewClick)))
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  
  func titleViewClick() -> Void {
    if let listen = titleClickListener {
      listen()
    }
  }
}



internal class TXNormalItemView :NormalMDSingleButton {
  
  private var itemHeight:CGFloat = 0
  
  private var half_height:CGFloat {
    get {
      return itemHeight / 2
    }
  }
  
  private var normalIcon:String! = nil {
    
    didSet {
      if let imageStr = normalIcon {
        
        self.iconIMageView.image = UIImage(named: imageStr)
        
      }else {
        self.iconIMageView.image = nil
      }
    }
    
  }
  
  private var highlightedIcon:String? = nil
  
  internal lazy var iconIMageView:UIImageView = {
    [unowned self] in
    let imageView = UIImageView()
    imageView.frame.width = self.half_height
    imageView.frame.height = self.half_height
    imageView.center.x = self.half_height
    imageView.center.y = self.half_height
    self.addSubview(imageView)
    return imageView
    }()
  
  internal lazy var itemTitleLabel:UILabel = {
    [unowned self] in
    let label = UILabel()
    label.font = UIFont.systemFont(ofSize: 16)
    label.text = "x"
    label.textColor = UIColor.ondC20Color()
    label.sizeToFit()
    label.frame.left = self.itemHeight
    label.center.y = self.half_height
    label.frame.width  = 120
    self.addSubview(label)
    return label
    }()
  
  internal lazy var descLabel:UILabel = {
    [unowned self] in
    
    
    let leftOffSet:CGFloat = self.showArrowFlag ? 30 : 8
    let descLabel = UILabel()
    descLabel.text = "测试"
    descLabel.textAlignment = .right
    descLabel.textColor = UIColor.init(white: 146.0/255.0, alpha: 1.0)
    descLabel.font = UIFont.systemFont(ofSize: 16)
    descLabel.sizeToFit()
    descLabel.center.y = self.half_height
    descLabel.frame.width = kMainScreenWidth - 164 - 30
    descLabel.frame.left = self.itemTitleLabel.frame.right + 3
    self.addSubview(descLabel)
    return descLabel
    
    }()
  
  internal fileprivate(set) var  layoutTag:Int = 0
  
  
  internal var showPublicTypeFlag:Bool = false {
    
    
    didSet {
      
      if self.showPublicTypeFlag {
        
        if _showPublicTypeView == nil {
          let publicTypeLabel = UILabel()
          publicTypeLabel.textColor = UIColor.white
          publicTypeLabel.font = UIFont.systemFont(ofSize: 14)
          publicTypeLabel.backgroundColor = UIColor.red
          publicTypeLabel.text = "私"
          publicTypeLabel.textAlignment = .center
          publicTypeLabel.frame = CGRect(x: 0 , y: (self.frame.height - 25)/2, width: 25, height: 25)
          publicTypeLabel.frame.right = self.showArrowFlag ? self._arrowImageView!.left - 3 : self.frame.width - 8
          _showPublicTypeView = publicTypeLabel
          self.addSubview(_showPublicTypeView!)
          
          self.descLabel.width = publicTypeLabel.frame.left - self.itemTitleLabel.right - 6
        }
      }else {
        if _showPublicTypeView != nil {
          _showPublicTypeView?.removeFromSuperview()
          _showPublicTypeView = nil
          self.descLabel.width = self.showArrowFlag ? self._arrowImageView!.left - 3 - self.itemTitleLabel.frame.right - 3 : self.frame.width - 8 - self.itemTitleLabel.frame.right - 3
        }
        
      }
      
    }
    
  }
  
  fileprivate var _showPublicTypeView:UILabel? = nil
  
  
  fileprivate var _arrowImageView:UIImageView? = nil
  
  fileprivate var _lineLayer:CALayer? = nil
  
  fileprivate var showLineFlag:Bool = false {
    
    didSet {
      
      if showLineFlag {
        if _lineLayer == nil {
          let line = CALayer()
          line.frame = CGRect(x: itemHeight,y: self.frame.height - kSingleLinePx,width: self.frame.width - itemHeight,height: kSingleLinePx)
          line.backgroundColor = UIColor.navigationLineColor().cgColor
          self.layer.addSublayer(line)
          _lineLayer = line
        }
      }else {
        if _lineLayer != nil {
          _lineLayer!.removeFromSuperlayer()
          _lineLayer = nil
        }
      }
    }
    
  }
  
  fileprivate var showArrowFlag:Bool = false {
    
    didSet {
      
      if showArrowFlag {
        if _arrowImageView == nil {
          _arrowImageView = UIImageView(image: UIImage(named: "show_next"))
          _arrowImageView!.sizeToFit()
          _arrowImageView!.center.y = half_height
          _arrowImageView!.frame.right = self.frame.width - 10
          self.addSubview(_arrowImageView!)
        }
      }else {
        if _arrowImageView != nil {
          _arrowImageView!.removeFromSuperview()
          _arrowImageView = nil
        }
      }
    }
  }
  
  
  class func initWith(iconNormal:String,iconHighliaghted:String,title:String,desc:String?,showArrowFlag:Bool,showLine:Bool,layoutTag:Int)->TXNormalItemView {
    
    let containerView = TXNormalItemView(frame: CGRect(x: 0, y: 0, width: kMainScreenWidth, height: 44))
    containerView.backgroundColor = UIColor.white
    containerView.itemHeight = containerView.frame.height
    containerView.showArrowFlag = showArrowFlag
    containerView.showLineFlag = showLine
    containerView.layoutTag = layoutTag
    
    
    containerView.normalIcon = iconNormal
    containerView.highlightedIcon = iconHighliaghted
    
    containerView.iconIMageView.image =  UIImage(named:iconNormal)
    containerView.itemTitleLabel.text = title
    containerView.setBrief(desc: desc)
    containerView.backgroundColor = UIColor.white
    return containerView
  }
  
  internal func setBrief(desc:String?){
    self.descLabel.text = desc
    if let _ = desc , let highlightedIcon = self.highlightedIcon {
      self.iconIMageView.image =  UIImage(named:highlightedIcon)
    }else {
      self.iconIMageView.image = UIImage(named:self.normalIcon)
    }
  }
  
}



public class TXBaseViewController: UIViewController
{
  
  var shouldLoad: Bool = true
  
  var progressManager: TXProgressManager! = nil
  
  var naviBar:TXNavigationBar! = nil
  
  var modelFlag:Bool = false
  // =============================================================================================
  // MARK:复写 viewDidLoad生命周期
  // =============================================================================================
  override final public func viewDidLoad() {
    super.viewDidLoad()
    self.hankBase()
    self.initBase()
    self.hankViewDidLoad()
    self.initNavigationBar()
    self.initView()
    self.initListener()
    self.hankViewDidLoadLast()
    self.initData()
  }
  
  fileprivate func hankViewDidLoadLast() {
    toProgress()
    self.progressManager.showProgressFlag = needShowProgress()
    //    self.naviBar.hidden = true
    if self.naviBar.superview != nil {
      self.view.bringSubview(toFront: self.naviBar)
    }
    
    if self.naviBar.title == nil{
      self.naviBar.title = self.title
    }
    
  }
  
  internal func hankBase() {
  }
  
  internal func initView() {
  }
  
  internal func initListener() {
  }
  
  internal func initData() {
  }
  
  internal func hankViewDidLoad() {
  }
  
  
  fileprivate func initNavigationBar(){
    naviBar = TXNavigationBar()
    self.view.addSubview(naviBar)
    
    naviBar.leftBt = leftBarButton()
    naviBar.rightBt = rightBarButton()
    
  }
  
  
  
  fileprivate final func initBase() {
    
    // 去除 NavigationBar 黑线
    //    self.hideNavigationBlackView()
    self.navigationController?.navigationBar.isHidden = true
    self.view.backgroundColor = UIColor.bgColor()
    self.automaticallyAdjustsScrollViewInsets = false
    weak var weakSelf = self
    self.progressManager = TXProgressManager(baseVC: weakSelf)
    if UIApplication.shared.isStatusBarHidden {
      UIApplication.shared.setStatusBarHidden(false, with: .slide)
    }
    //    IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
    
    
  }
  
  override public func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    //    self.navigationController?.interactivePopGestureRecognizer?.delegate = self
  }
  
  func loadModel() {
  }
  
  // help  MARK: TODO  返回值问题
  func previousController() -> UIViewController? {
    if self.navigationController == nil {
      return nil
    }
    
    if self.navigationController?.viewControllers.count == 1 {
      return nil
    }
    
    return self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)! - 2]
  }
  
  func popToVC(_ index: Int = 1, animtion: Bool = true) {
    
    if index == 1 {
      self.navigationController?.popViewController(animated: animtion)
      return
    }
    
    if let navigationController = self.navigationController {
      let count = navigationController.viewControllers.count
      navigationController.popToViewController(navigationController.viewControllers[count - index - 1], animated: animtion)
    }
  }
  
  override public func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  override public func viewDidDisappear(_ animated: Bool) {
    super.viewDidAppear(animated)
  }
  
  func showErrorMsgWithJson(_ json: JSON?) {
    if json != nil {
      if let msg = json!["msg"].string {
        showToast(msg)
      }
    }
  }
  
  func transFormStringToNSURL(_ str:String?)->URL? {
    guard let s = str else {
      return nil
    }
    return URL(string: s)
  }
  
  
  
  func dismissVC(_ animationFlag:Bool,completion:(()->())?){
    if self.modelFlag {
      self.dismiss(animated: animationFlag, completion: completion)
    }else {
      if let navigationController = self.navigationController {
        navigationController.popViewController(animated: animationFlag)
      }
    }
  }
  
  override public func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) {
    
    if viewControllerToPresent.isKind(of: UINavigationController.self){
      if let vc = ((viewControllerToPresent as! UINavigationController).viewControllers[0] as? TXBaseViewController) {
        vc.modelFlag = true
      }
    }else {
      if let vc = (viewControllerToPresent as? TXBaseViewController) {
        vc.modelFlag = true
      }
    }
    
    super.present(viewControllerToPresent, animated: flag, completion: completion)
  }
  
  override public func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
  }
  override public func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
  }
  
  func pushVC(_ targetVC: UIViewController, WithAnimation flag: Bool = true) {
    self.navigationController?.pushViewController(targetVC, animated: flag)
  }
  
  
  deinit {
    self.deinitHank()
  }
  
  
  open func deinitHank(){
    TXLogDebug("释放UIViewController:\(self.tx_className())")
  }
  
}
// MARK: 扩展 ProgressLoadView实现
extension TXBaseViewController {
  
  internal func needShowProgress() -> Bool {
    return true
  }
  
  internal func toMain() {
    self.progressManager.toMain()
  }
  
  internal func toProgress() {
    self.progressManager.toProgress()
  }
  
  internal func toError() {
    self.progressManager.toError()
  }
  
  internal func toEmpty(_ titleStr: String) {
    self.progressManager.toEmpty(titleStr)
  }
  
  internal func errorViewClick() {
    TXLogError("errorViewClick")
  }
  
  internal func emptyViewClick() {
    TXLogError("emptyViewClick")
  }
  
  internal func setProgressView(progressView view: UIView) {
    //    self.progressLoadView?.setProgressView(progressView: view)
  }
  
  internal func setEmptyView(emptyView view: UIView) {
    self.progressManager?.setEmptyView(emptyView: view)
  }
  
  internal func setErrorView(errorView view: UIView) {
    self.progressManager?.setErrorView(errorView: view)
  }
}

// MARK: 扩展 navigationBar实现
extension TXBaseViewController {
  
  func leftBarButton() -> UIButton? {
    
    if self.modelFlag {
      let cancleBtn = NormalMDSingleButton()
      cancleBtn.backgroundColor = nil
      cancleBtn.frame = CGRect(x: 0, y: 20, width: 54, height: 44)
      cancleBtn.setTitle("取消", for: .normal)
      cancleBtn.setTitleColor(UIColor.ondC5Color(), for: .normal)
      cancleBtn.setSingleClickListener{
        [unowned self] in
        
        if self.modelFlag {
          self.dismissVC(true, completion: nil)
        }else {
          if let navigationController = self.navigationController {
            navigationController.popViewController(animated: true)
          }
        }
      }
      return cancleBtn
      
    }else {
      
      let backBtn = NormalMDSingleButton()
      backBtn.backgroundColor = nil
      backBtn.frame = CGRect(x: 0, y: 20, width: 44, height: 44)
      let image = UIImage(named: "back_btn")
      backBtn.setImage(image, for: .normal)
      backBtn.setImage(image, for: .highlighted)
      backBtn.setSingleClickListener{
        [weak self] in
        if let navigationController = self?.navigationController {
          navigationController.popViewController(animated: true)
        }
      }
      return backBtn
    }
    
  }
  
  func rightBarButton() -> UIButton? {
    return nil
  }
  
  func isNeedTabBar() -> Bool {
    return true
  }
}

extension UIViewController {
  func showToast(_ msg: String, delay: TimeInterval = 1.5) {
    
    SVProgressHUD.showInfo(withStatus: msg)
    Timer.schedule(delay: delay) {
      timer in
      SVProgressHUD.dismiss()
    }
  }
  
  func showProgress() -> Void {
    //    SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black)
    SVProgressHUD.setDefaultStyle(SVProgressHUDStyle.dark)
    SVProgressHUD.setDefaultAnimationType(.native)
    SVProgressHUD.setMinimumSize(CGSize(width: 60, height: 60))
    SVProgressHUD.setFadeOutAnimationDuration(0.4)
    SVProgressHUD.showProgress(-1)
    
  }
  
  func dismissProgress() -> Void {
    SVProgressHUD.dismiss()
  }
  
}
